﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using BookiFramework.Abstracts.Security;

namespace BookiFramework.Security.Cryptography
{
    public class TripleDESCrypter : ICrypter
    {
        private byte[] _iv;
        private byte[] _key;        

        public byte[] Crypt(string text)
        {
            var encoding = new UTF8Encoding();

            byte[] message = encoding.GetBytes(text);

            var criptoProvider = new TripleDESCryptoServiceProvider();

            _iv = criptoProvider.IV;
            _key = criptoProvider.Key;

            ICryptoTransform criptoTransform =criptoProvider.CreateEncryptor(_key, _iv);

            var memoryStream = new MemoryStream();

            var cryptoStream = new CryptoStream(memoryStream,criptoTransform,CryptoStreamMode.Write);

            cryptoStream.Write(message, 0, message.Length);
            cryptoStream.FlushFinalBlock();

            var cryptedBytes = memoryStream.ToArray();
            return cryptedBytes;
        }

        public string CryptToText(string text)
        {
            var encoding = new UTF8Encoding();
            var cryptedBytes = Crypt(text);
            var cryptedString = encoding.GetString(cryptedBytes);            
            return cryptedString;
        }

        public string Decrypt(string text)
        {
            var encoding = new UTF8Encoding();
            var crypto = encoding.GetBytes(text);            
            return Decrypt(crypto);
        }
        public string Decrypt(byte[] crypto)
        {
            var cryptoProvider = new TripleDESCryptoServiceProvider(); 
            ICryptoTransform cryptoTransform = cryptoProvider.CreateDecryptor(_key,_iv);
            var memoryStream = new MemoryStream(crypto);		
            var cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Read); 		
            var sr = new StreamReader(cryptoStream,true);		
            var decryptedString = sr.ReadToEnd();		
            return decryptedString;		
        }
    }
}
